const { untTokenUrl } = require('../conf')
const { serect } = require('../conf')
const tokenObj = require('./token')
const dbutil = require('../libs/MyDB')
const qs = require('querystring')




module.exports = async function (req, res, next) {

    let urlLib = req.url;

    if (urlLib.indexOf('?') > 0) {
        urlLib = urlLib.substr(0, urlLib.indexOf('?'))
    }

    if (req.moduleName == 'api') {
        if (untTokenUrl.indexOf(urlLib) < 0) {

            // 验证user-token是否存在

            if (!req.headers || !req.headers['user-token']) {
                res.send({
                    code: 402,
                    msg: "you not allowed"
                });
                return;
            }


            try {

                let decoded = tokenObj.get_token(req.headers['user-token'], 'serect');

                let { token } = await dbutil.singleSelect('wb_user', 'token', `uid = '${decoded.uid}'`)

                let decoded1 = tokenObj.get_token(token, 'serect');
                
                if (req.headers['user-token'] != token) {
                    res.send({
                        code: 411,
                        msg: 'token is different'
                    })
                    return;
                }

                req.userData = decoded
                next()

            } catch (error) { //Token过期
                console.log(error);
                res.send({
                    code: 410,
                    msg: "you not allowed"
                });
                return;
            }


        }
        else {
            next()
        }
    } else {
        next()
    }

}
